import React, { Component } from 'react'
import GoBack from '@/components/TheGoBack'
import '@/views/commodity/style/style.less'
import { Button, Table, Tooltip } from 'antd'
import { QuestionCircleOutlined } from "@ant-design/icons"
import TheImage from '@/components/TheImage'
import { apiGetStandOrderDetail } from '@/request/cashier'
import _ from 'lodash'
import axios from 'axios'

export default class OrderDetails extends Component {
  state = {
    basicData: [],
    columns: [
      {
        title: "商品信息",
        width: 600,
        render: (text, record) => {
          let style = {
            width: 200,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis'
          }
          return (
            <div style={{ display: "flex", alignItems: "center" }}>
              <TheImage
                src={record.productImage}
                width={100}
              />
              <div style={{ margin: "0 10px" }}>{record.productName}</div>
              <div>{record.sku}</div>
            </div>
          );
        },
      },
      {
        title: "单价",
        dataIndex: "orderPrice",
        key: "orderPrice",
        render: (text) => <React.$price price={text || 0} />,
      },
      {
        title: "商品数量",
        dataIndex: "orderProductCount",
        key: "orderProductCount",
        render: (text) => text || 0,
      },
      {
        title: "满件优惠金额",
        dataIndex: "productMaxOutPrice",
        key: "productMaxOutPrice",
        render: (text) => <React.$price price={text || 0} />,
      },
      {
        title: "合计",
        dataIndex: "orderPriceTotal",
        key: "orderPriceTotal",
        render: (text, record) => {
          return <div>
            <React.$price color="red" price={ text-record.productMaxOutPrice || 0} />
          </div>
        },
      },
    ],
    dataSource: [],
    serviceData: [],
    serviceColumns: [
      {
        title: '服务名称',
        dataIndex: 'productName',
        key: 'productName'
      },
      {
        title: '价格',
        dataIndex: 'orderPrice',
        key: 'orderPrice',
        render: (text, record) => {
          return <React.$Price price={text || 0} />
        }
      },
      {
        title: '美容师',
        dataIndex: 'shoppingBeauticianName',
        key: 'shoppingBeauticianName',
        render: (text, record) => {
          return record.shoppingBeauticianName ? record.shoppingBeauticianName : "/"
        }
      },
    ],
    otherColumns: [
      {
        title: '备注',
        dataIndex: 'orderProductRemark',
        key: 'orderProductRemark'
      },
      {
        title: '金额',
        dataIndex: 'orderPrice',
        key: 'orderPrice',
        render: (text, record) => {
          return <React.$Price price={text || 0} />
        }
      }
    ],
    couponColumns: [
      {
        title: '赠送类型',
        dataIndex: 'discountType',
        key: 'discountType'
      },
      {
        title: '名称',
        dataIndex: 'couponTitle',
        key: 'couponTitle'
      },
      {
        title: '数量',
        dataIndex: 'count',
        key: 'count'
      },
    ],
    printData: [],
    hide: false, //从收银台显示隐藏返回按钮
    couponData: []
  }
  componentDidMount() {
    this.getData()
  }
  getData = async () => {
    let id = ''
    if (this.props.match) {
      id = this.props.match.params.id
    }
    else {
      id = this.props.id
      this.setState({
        hide: true
      })
    }
    let res = await apiGetStandOrderDetail({ orderId: id })
    if (res.data && res.code === 0) {
      let data = res.data
      let basicData = [
        {
          text: '订单编号',
          value: data.orderCode
        },
        {
          text: '订单时间',
          value: data.createTime
        },
        {
          text: '用户昵称',
          value: data.orderMemberName || '无'
        },
        {
          text: '收款人员',
          value: data.cashierName
        },
        {
          text: '导购员',
          value: data.shoppingGuideName ? data.shoppingGuideName : "/"
        },
        {
          text: '支付方式',
          value: data.payWay || '未支付'
        },
        {
          text: '商品折扣',
          value: data.productDiscount ? data.productDiscount + "%" : "/"
        },
        {
          text: '服务折扣',
          value: data.serviceDiscount !== null ? data.serviceDiscount + "%" : "/"
        },
        {
          text: '折扣立减',
          value: <React.$Price color="#7F7F7F" price={data.couponTotal} />
        },
        {
          text: '满件优惠',
          value: <React.$Price color="#7F7F7F" price={data.productMaxOutPrice} />
        },
        {
          text: '优惠券立减',
          value: data.couponDiscountTotal
            ? <><React.$Price color="#7F7F7F" price={data.couponDiscountTotal} /> &nbsp;
              {data.memberCouponList.length > 0 ? <Tooltip title={data.memberCouponList.map((res) => {
                return <p>{res.memberCoupon.couponTitle + " X " + res.count}</p>
              })}><QuestionCircleOutlined /> </Tooltip> : <Tooltip title="已退款，优惠券已退回" ><QuestionCircleOutlined /> </Tooltip>
              }
            </>
            : <React.$Price color="#7F7F7F" price={data.couponDiscountTotal} />
        },
        {
          text: '应收金额',
          value: <React.$Price color="#7F7F7F" price={data.serviceTotalPrice + data.productTotalPrice + data.otherTotalPrice} />
        },
        {
          text: '实收金额',
          value: <React.$Price color="#7F7F7F" price={(data.orderTotalPrice || 0) - (data.couponTotal || 0) - (data.couponDiscountTotal || 0) - (data.productMaxOutPrice || 0) + (data.cashChange || 0)} />
        },
        {
          text: '找零',
          value: <React.$Price color='#7f7f7f' price={data.cashChange || 0} />
        },
        {
          text: '折扣备注',
          value: data.discountRemark ? data.discountRemark : "/"
        },
      ]
      let basicPayPrice = data.payData.map(item => {
        switch (item.payWay) {
          case 'Cash':
            return ({
              text: '现金支付',
              value: <><React.$Price color="#7F7F7F" price={item.payPrice} />  备注：{item.payWayDescription}</>
            })
            break;
          case 'Other':
            return ({
              text: '其他支付',
              value: <><React.$Price color="#7F7F7F" price={item.payPrice} />  备注：{item.depositCardNumber}</>
            })
            break;
          case 'Wallet':
            return ({
              text: '余额支付',
              value: <React.$Price color="#7F7F7F" price={item.payPrice} />
            })
            break;
          case 'Other':
            return ({
              text: '其他支付',
              value: <><React.$Price color="#7F7F7F" price={item.payPrice} />  备注：{item.depositCardNumber}</>
            })
            break;
          case 'WeChat':
            return ({
              text: '微信支付',
              value: <React.$Price color="#7F7F7F" price={item.payPrice} />
            })
            break;
          case 'Alipay':
            return ({
              text: '支付宝支付',
              value: <React.$Price color="#7F7F7F" price={item.payPrice} />
            })
            break;
          case 'RemoteAlipay':
            return ({
              text: '扫码支付(支付宝)',
              value: <React.$Price color="#7F7F7F" price={item.payPrice} />
            })
            break;
          case 'RemoteWeChat':
            return ({
              text: '扫码支付(微信)',
              value: <React.$Price color="#7F7F7F" price={item.payPrice} />
            })
            break;
          default:
            break;
        }

      })
      let integralData = [
        {
          text: '赠送积分',

          value: _.toNumber(data.presentIntegral).toLocaleString()
        }
      ]
      basicData = _.concat(basicData, integralData, basicPayPrice)
      // basicData = _.concat(basicData, basicPayPrice, integralData)
      let dataSource = data.standProductList.map(v => {
        let productSkuJson = JSON.parse(v.productSkuJson)
        let sku = productSkuJson.skuAttribute.map(k => k.product_value)
        return {
          ...v,
          sku
        }
      })
      let balance = []
      let couponList = []
      if (data.standOrderDetailOtherInfoVo) {
        balance = [{ discountType: "余额", couponTitle: "-", count: _.toNumber(React.$transNum(data.standOrderDetailOtherInfoVo.balance, 2, -2)) + "元" }]
        couponList = data.standOrderDetailOtherInfoVo.couponInfoCountList.map(res => {
          return {
            discountType: "优惠券",
            couponTitle: res.memberCoupon.couponTitle,
            count: res.count + "张"
          }
        })
      }
      let serviceData = data.standServiceList
      let otherData = data.standOtherList
      let couponData = couponList.concat(balance)
      let printData = res.data
      this.setState({
        basicData,
        dataSource,
        serviceData,
        otherData,
        couponData,
        printData
      })
    }
  }
  print = () => {
    const { printData } = this.state
    let token = sessionStorage.getItem('RSnetToken')
    React.$post('/management/storeInfo/storePrinterName').then(response => {
      const { receiptPrinterName } = response.data
      axios.post(`http://localhost:8888/admin/bill/print/${receiptPrinterName}`, { ...printData }, {
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'RSnetToken': token,
          'Accept': '*/*'
        }
      })
    })
  }
  render() {
    const { basicData, columns, dataSource, serviceData, serviceColumns, otherData, otherColumns, hide, couponColumns, couponData } = this.state
    return (
      <div className="p-layout-box commodity-list-detail">
        {hide ? '' : <GoBack history={this.props.history} title={"订单详情"} />}
        <div className="detail-content">
          <div className="commodity-card">
            <div className="title" style={{ position: 'relative' }}>
              <span>基本信息</span>
              <Button onClick={this.print} type='primary' style={{ borderRadius: 8, position: 'absolute', top: 16, right: 20 }}>补打小票</Button>
            </div>
            <div className="content basic" style={{ padding: '20px 60px' }}>
              {basicData.map((v, i) => {
                return (
                  <div>
                    <p style={{ minWidth: 90 }}>{v.text}:</p>
                    <div>{v.value}</div>
                  </div>
                );
              })}
            </div>
          </div>
          {!_.isEmpty(dataSource) && <div className="commodity-card">
            <div className="title">商品列表</div>
            <div className="content">
              <Table
                dataSource={dataSource}
                columns={columns}
                pagination={false}
                summary={(pageData) => {
                  let totalOrderPriceTotal = 0;
                  let totalOrderProductCount = 0;
                  pageData.forEach(
                    ({ orderPriceTotal, orderProductCount, productMaxOutPrice, integral }) => {
                      totalOrderPriceTotal += orderPriceTotal - productMaxOutPrice || 0;
                      totalOrderProductCount += orderProductCount || 0;
                    }
                  );
                  return (
                    <>
                      <Table.Summary.Row>
                        <Table.Summary.Cell colSpan={24}>
                          <div style={{ textAlign: "center" }}>
                            {`共${totalOrderProductCount}件商品，总计：`}
                            <React.$price color="red" price={totalOrderPriceTotal  || 0} />
                          </div>
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                    </>
                  );
                }}
              />
            </div>
          </div>}
          {!_.isEmpty(serviceData) && <div className="commodity-card">
            <div className="title">服务列表</div>
            <div className="content">
              <Table
                dataSource={serviceData}
                columns={serviceColumns}
                pagination={false}
                summary={(pageData) => {
                  let totalOrderPriceTotal = 0;
                  let totalOrderProductCount = 0;
                  pageData.forEach(
                    ({ orderPriceTotal, orderProductCount }) => {
                      totalOrderPriceTotal += orderPriceTotal || 0;
                      totalOrderProductCount += orderProductCount || 0;
                    }
                  );
                  return (
                    <>
                      <Table.Summary.Row>
                        <Table.Summary.Cell colSpan={24}>
                          <div style={{ textAlign: "center" }}>
                            {`共${totalOrderProductCount}项服务，总计：`}
                            <React.$price color="red" price={totalOrderPriceTotal || 0} />
                          </div>
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                    </>
                  );
                }}
              />
            </div>
          </div>}
          {!_.isEmpty(otherData) && <div className="commodity-card">
            <div className="title">其他服务</div>
            <div className="content">
              <Table
                dataSource={otherData}
                columns={otherColumns}
                pagination={false}
              />
            </div>
          </div>}
          {!_.isEmpty(couponData) && <div className="commodity-card">
            <div className="title">其他</div>
            <div className="content">
              <Table
                dataSource={couponData}
                columns={couponColumns}
                pagination={false}
              />
            </div>
          </div>}
        </div>
      </div>
    )
  }
}
